package com.definesys.smecrailtransit.module.MonthForm.ViewController;

import android.view.View;

import com.definesys.smecrailtransit.R;
import com.definesys.smecrailtransit.SmecManager.SmecRealm.RealmManager;
import com.definesys.smecrailtransit.api.SmecRailApi;
import com.definesys.smecrailtransit.bean.ApplyBean;
import com.definesys.smecrailtransit.bean.LineBean;
import com.definesys.smecrailtransit.bean.StationBean;
import com.definesys.smecrailtransit.databinding.FragmentMonthFormBinding;
import com.definesys.smecrailtransit.module.MonthForm.MonthFormPresenter;
import com.definesys.smecrailtransit.adapter.SelctLineAdapter.SelectLineAdapter;
import com.definesys.smecrailtransit.adapter.SelectMonthAdapter.SelectMonthAdapter;
import com.definesys.smecrailtransit.adapter.SelectUserAdapter.SelectUserAdapter;
import com.definesys.smecrailtransit.module.MonthForm.bean.PositionBean;
import com.definesys.smecrailtransit.module.MonthForm.bean.StatisticBean;
import com.definesys.smecrailtransit.utils.CommonUtils;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;

import io.realm.RealmResults;


/**
 * Created by cjy on 2017/7/27.
 */

public class ViewController {
    private String selectUser;
    private String selectMonth;
    private String selectYear;
    private String selectLine;
    public String nowMonth;
    private String popMonth;
    private String eleContractNo;

    private ArrayList<StationBean> list;
    private ArrayList<PositionBean> popWindowList;
    private ArrayList<ApplyBean> userList;
    private ArrayList<String> lineList;
    private ArrayList<String> yearList;
    private ArrayList<String> popMonthList;

    private FragmentMonthFormBinding fragmentMonthFormBinding;
    private MonthFormPresenter monthFormPresenter;
    protected RealmManager realmManager;

    private SelectMonthAdapter selectMonthAdapter;
    private SelectUserAdapter selectUserAdapter;
    private SelectLineAdapter selectLineAdapter;


    public ViewController(FragmentMonthFormBinding fragmentMonthFormBinding,MonthFormPresenter monthFormPresenter){
        this.fragmentMonthFormBinding = fragmentMonthFormBinding;
        this.monthFormPresenter = monthFormPresenter;
        this.realmManager=RealmManager.getInstance();

        this.list = new ArrayList<>();
        this.popWindowList = new ArrayList<>();
        this.userList = new ArrayList<>();
        this.lineList = new ArrayList<>();
        this.yearList = new ArrayList<>();
        this.popMonthList = new ArrayList<>();

        this.selectLine = "12号线";
        this.selectUser = "全部运营商";

        this.popMonthList.add("一个月");
        this.popMonthList.add("三个月");
        this.popMonthList.add("半年");
        this.popMonth = "一个月";

        //获取系统时间
        SimpleDateFormat sDateFormat =  new SimpleDateFormat("yyyy-MM");
        String date = sDateFormat.format(new java.util.Date());
        this.selectMonth = date.substring(5,7);
        this.nowMonth = date.substring(5,7);
        if( !this.selectMonth.equals("10") || !this.selectMonth.equals("11") || !this.selectMonth.equals("12")){
            this.selectMonth = date.substring(6,7);
            this.nowMonth = date.substring(6,7);
        }

        this.selectYear = date.substring(0,4);

        //设置可选的年份数组
        int year = Integer.valueOf(this.selectYear);
        for(int i = 0 ; i < 3; i++){
            this.yearList.add(String.valueOf(year-2+i));
        }

        //设置dialog背景层的点击事件
        fragmentMonthFormBinding.backgroundChoice.setOnClickListener(v -> {
            fragmentMonthFormBinding.choice.setVisibility(View.GONE);
        });
        fragmentMonthFormBinding.backgroundPull.setOnClickListener(v -> {
            fragmentMonthFormBinding.pull.setVisibility(View.GONE);
            fragmentMonthFormBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);

        });
        fragmentMonthFormBinding.line.setOnClickListener(v -> {
            fragmentMonthFormBinding.line.setVisibility(View.GONE);
            fragmentMonthFormBinding.lineImg.setBackgroundResource(R.drawable.month_form_bottom);
        });

        //设置月份下拉列表点击事件
        fragmentMonthFormBinding.choiceMonth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //检测当前是否已经到了下一个月
                checkMonth();

                selectMonthAdapter.selectMonth = selectMonth;
                selectMonthAdapter.nowMonth = nowMonth;
                selectMonthAdapter.notifyDataSetChanged();
                fragmentMonthFormBinding.invalidateAll();

                if(fragmentMonthFormBinding.choice.getVisibility() == View.GONE){
                    fragmentMonthFormBinding.choice.setVisibility(View.VISIBLE);
                }else{
                    fragmentMonthFormBinding.choice.setVisibility(View.GONE);
                }
                fragmentMonthFormBinding.line.setVisibility(View.GONE);
                fragmentMonthFormBinding.lineImg.setBackgroundResource(R.drawable.month_form_bottom);
                fragmentMonthFormBinding.pull.setVisibility(View.GONE);
                fragmentMonthFormBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);
            }
        });

        //设置线路下拉列表点击事件
        fragmentMonthFormBinding.choiceLine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectLineAdapter.notifyDataSetChanged();
                if(fragmentMonthFormBinding.line.getVisibility() == View.GONE){
                    fragmentMonthFormBinding.line.setVisibility(View.VISIBLE);
                    fragmentMonthFormBinding.lineImg.setBackgroundResource(R.drawable.month_form_top);
                }else{
                    fragmentMonthFormBinding.line.setVisibility(View.GONE);
                    fragmentMonthFormBinding.lineImg.setBackgroundResource(R.drawable.month_form_bottom);
                }
                fragmentMonthFormBinding.choice.setVisibility(View.GONE);
                fragmentMonthFormBinding.pull.setVisibility(View.GONE);
                fragmentMonthFormBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);
            }
        });

        //设置运营商下拉列表点击事件
        fragmentMonthFormBinding.choiceUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectUserAdapter.select_user = selectUser;
                selectUserAdapter.notifyDataSetChanged();
                fragmentMonthFormBinding.invalidateAll();

                if(fragmentMonthFormBinding.pull.getVisibility() == View.GONE){
                    fragmentMonthFormBinding.pull.setVisibility(View.VISIBLE);
                    fragmentMonthFormBinding.userImg.setBackgroundResource(R.drawable.month_form_top);
                }else{
                    fragmentMonthFormBinding.pull.setVisibility(View.GONE);
                    fragmentMonthFormBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);
                }
                fragmentMonthFormBinding.line.setVisibility(View.GONE);
                fragmentMonthFormBinding.lineImg.setBackgroundResource(R.drawable.month_form_bottom);
                fragmentMonthFormBinding.choice.setVisibility(View.GONE);
            }
        });

        //设置月份左右选择按钮点击事件
        if(this.selectMonth.equals("7")){
            this.fragmentMonthFormBinding.selectPreviousMonthImg.setVisibility(View.GONE);
        }
        if(this.selectMonth.equals(this.nowMonth)){
            ViewController.this.fragmentMonthFormBinding.selectNextMonthImg.setVisibility(View.GONE);
        }
        fragmentMonthFormBinding.selectPreviousMonth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!ViewController.this.selectMonth.equals("7")){
                    ViewController.this.selectMonth = String.valueOf(Integer.valueOf(ViewController.this.selectMonth) -1);
                    ViewController.this.selectMonthAdapter.selectMonth = ViewController.this.selectMonth;
                    ViewController.this.selectMonthAdapter.notifyDataSetChanged();
                    ViewController.this.fragmentMonthFormBinding.nowMonth.setText(ViewController.this.getSelectYear()+"年 "+ViewController.this.getSelectMonth()+"月");

                    if(ViewController.this.fragmentMonthFormBinding.selectNextMonthImg.getVisibility() == View.GONE){
                        ViewController.this.fragmentMonthFormBinding.selectNextMonthImg.setVisibility(View.VISIBLE);
                    }

                    if(ViewController.this.selectMonth.equals("7")){
                        ViewController.this.fragmentMonthFormBinding.selectPreviousMonthImg.setVisibility(View.GONE);
                    }

                    ViewController.this.fragmentMonthFormBinding.choice.setVisibility(View.GONE);
                    ViewController.this.fragmentMonthFormBinding.invalidateAll();
                    ViewController.this.getNetWorkData();
                    ViewController.this.getLocalData();
                }
                fragmentMonthFormBinding.pull.setVisibility(View.GONE);
                fragmentMonthFormBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);
            }
        });

        fragmentMonthFormBinding.selectNextMonth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!ViewController.this.selectMonth.equals(ViewController.this.nowMonth)){
                    ViewController.this.selectMonth = String.valueOf(Integer.valueOf(ViewController.this.selectMonth) + 1);
                    ViewController.this.selectMonthAdapter.selectMonth = ViewController.this.selectMonth;
                    ViewController.this.selectMonthAdapter.notifyDataSetChanged();
                    ViewController.this.fragmentMonthFormBinding.nowMonth.setText(ViewController.this.getSelectYear()+"年 "+ViewController.this.getSelectMonth()+"月");

                    if(ViewController.this.fragmentMonthFormBinding.selectPreviousMonthImg.getVisibility() == View.GONE){
                        ViewController.this.fragmentMonthFormBinding.selectPreviousMonthImg.setVisibility(View.VISIBLE);
                    }

                    if(ViewController.this.selectMonth.equals(ViewController.this.nowMonth)){
                        ViewController.this.fragmentMonthFormBinding.selectNextMonthImg.setVisibility(View.GONE);
                    }

                    ViewController.this.fragmentMonthFormBinding.choice.setVisibility(View.GONE);
                    ViewController.this.fragmentMonthFormBinding.invalidateAll();
                    ViewController.this.getNetWorkData();
                    ViewController.this.getLocalData();
                }
                fragmentMonthFormBinding.pull.setVisibility(View.GONE);
                fragmentMonthFormBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);
            }
        });


    }

    public ArrayList<StationBean> getList() {
        return list;
    }

    public void setList(ArrayList<StationBean> list) {
        this.list = list;
    }

    public ArrayList<ApplyBean> getUserList() {
        return userList;
    }

    public void setUserList(ArrayList<ApplyBean> userList) {
        this.userList = userList;
    }

    public String getSelectUser() {
        return selectUser;
    }

    public void setSelectUser(String selectUser) {
        this.selectUser = selectUser;
    }

    public String getSelectLine() {
        return selectLine;
    }

    public void setSelectLine(String selectLine) {
        this.selectLine = selectLine;
    }

    public ArrayList<String> getLineList() {
        return lineList;
    }

    public void setLineList(ArrayList<String> lineList) {
        this.lineList = lineList;
    }

    public FragmentMonthFormBinding getFragmentMonthFormBinding() {
        return fragmentMonthFormBinding;
    }

    public void setFragmentMonthFormBinding(FragmentMonthFormBinding fragmentMonthFormBinding) {
        this.fragmentMonthFormBinding = fragmentMonthFormBinding;
    }

    public ArrayList<PositionBean> getPopWindowList() {
        return popWindowList;
    }

    public void setPopWindowList(ArrayList<PositionBean> popWindowList) {
        this.popWindowList = popWindowList;
    }

    public String getSelectYear() {
        return selectYear;
    }

    public void setSelectYear(String selectYear) {
        this.selectYear = selectYear;
    }

    public String getSelectMonth() {
        return selectMonth;
    }

    public void setSelectMonth(String selectMonth) {
        this.selectMonth = selectMonth;
    }

    public SelectMonthAdapter getSelectMonthAdapter() {
        return selectMonthAdapter;
    }

    public void setSelectMonthAdapter(SelectMonthAdapter selectMonthAdapter) {
        this.selectMonthAdapter = selectMonthAdapter;
    }

    public SelectUserAdapter getSelectUserAdapter() {
        return selectUserAdapter;
    }

    public void setSelectUserAdapter(SelectUserAdapter selectUserAdapter) {
        this.selectUserAdapter = selectUserAdapter;
    }

    public SelectLineAdapter getSelectLineAdapter() {
        return selectLineAdapter;
    }

    public void setSelectLineAdapter(SelectLineAdapter selectLineAdapter) {
        this.selectLineAdapter = selectLineAdapter;
    }

    public ArrayList<String> getPopMonthList(){
        return this.popMonthList;
    }



    //获取数据
    public void getNetWorkData(){
        //设置参数
        HashMap<String, String> param = new HashMap<>();
        if(!this.getSelectMonth().equals("10") || !this.getSelectMonth().equals("11") || !this.getSelectMonth().equals("12")){
            param.put("date",this.getSelectYear() + "-0" + this.getSelectMonth());
        }else{
            param.put("date",this.getSelectYear() + "-" + this.getSelectMonth());
        }

        param.put("line",this.getSelectLine().substring(0,this.getSelectLine().length()-2));

        //网络请求
        this.monthFormPresenter.getMonthForm(param);

    }

    //获取本地数据
    public void getLocalData(){
        //获取线路数据
        RealmResults<LineBean> lineListRealm = (RealmResults<LineBean>)this.realmManager.findAllByKey(LineBean.class,"flag", SmecRailApi.MonthCode.MONTHFORM);
        ArrayList<LineBean> lineList = (ArrayList<LineBean>)this.realmManager.getRealm().copyFromRealm(lineListRealm);

        //获取运营商数据
        RealmResults<ApplyBean> applyList = (RealmResults<ApplyBean>)this.realmManager.findAllByKey(ApplyBean.class,"flag", SmecRailApi.MonthCode.MONTHFORM);
        this.userList = (ArrayList<ApplyBean>)this.realmManager.getRealm().copyFromRealm(applyList);
        ApplyBean allApply = new ApplyBean(-1,"全部运营商");
        this.userList.add(0,allApply);

        //获取站点信息
        String month;
        if(this.selectMonth.equals("10") || this.selectMonth.equals("11") || this.selectMonth.equals("12")){
            month = this.selectYear + "-" + this.selectMonth;
        }else{
            month = this.selectYear + "-0" + this.selectMonth;
        }
        int id=this.getNowLineId(lineList);
        if(this.selectUser.equals("全部运营商")){
            RealmResults<StationBean> stationList = (RealmResults<StationBean>)this.realmManager.findAllByKey(StationBean.class,"lineId",
                    id,"date",month, "flag", SmecRailApi.MonthCode.MONTHFORM);
             this.list = (ArrayList<StationBean>)this.realmManager.getRealm().copyFromRealm(stationList);
        }else{
            RealmResults<StationBean> stationList = (RealmResults<StationBean>)this.realmManager.findAllByKey(StationBean.class,"lineId",
                    id,"applyId",this.getNowApplyId(),"date",month,"flag", SmecRailApi.MonthCode.MONTHFORM);
            this.list = (ArrayList<StationBean>)this.realmManager.getRealm().copyFromRealm(stationList);
        }

        //排序处理
        ArrayList<StationBean> dataList = this.list;
        ArrayList<StationBean> resultList = new ArrayList<>();
        int length = this.list.size();
        for(int i = 0; i < length ;i++){

            int min = dataList.get(0).getSeq();
            int index =0;
            for(int j = 0; j < dataList.size() ;j++){
                if(dataList.get(j).getSeq() < min){
                    min = dataList.get(j).getSeq();
                    index = j;
                }
            }

            if(i != 0){
                if(resultList.get(i-1).getSeq() != dataList.get(index).getSeq()-1){
                    StationBean s = new StationBean();
                    s.setSeq(-1);
                    resultList.add(s);
                }
            }
            resultList.add(dataList.get(index));


            dataList.remove(index);
        }

        this.list = resultList;


        //检测当前是否已经到了下一个月
        if( checkMonth()){
            selectMonthAdapter.nowMonth = nowMonth;
            selectMonthAdapter.notifyDataSetChanged();

        }

        fragmentMonthFormBinding.invalidateAll();

    }

    private int getNowLineId(ArrayList<LineBean> lineList){

        if(CommonUtils.notEmpty(lineList)){
            for(int i=0 ;i<lineList.size();i++){
                if(lineList.get(i).getName().equals(this.selectLine)){
                    return lineList.get(i).getLineId();
                }
            }
            return lineList.get(0).getLineId();
        }
        return -1;
    }

    private int getNowApplyId(){
        for(int i=0 ;i<this.userList.size();i++){
            if(this.userList.get(i).getName().equals(this.selectUser)){
                return  this.userList.get(i).getApplyId();
            }
        }
        return this.userList.get(0).getApplyId();
    }

    private boolean checkMonth(){
        SimpleDateFormat sDateFormat =  new SimpleDateFormat("yyyy-MM");
        String date = sDateFormat.format(new java.util.Date());
        String month = date.substring(5,7);
        if( !month.equals("10") || !month.equals("11") || !month.equals("12")){
            month = date.substring(6,7);
        }
        if(!month.equals(ViewController.this.nowMonth)){
            ViewController.this.nowMonth = month;
            if(!ViewController.this.selectMonth.equals(ViewController.this.nowMonth)){
                ViewController.this.fragmentMonthFormBinding.selectNextMonthImg.setVisibility(View.VISIBLE);
            }
            return true;
        }
        return false;
    }


    //获取自动扶梯、升降梯、总计的数量
    public StatisticBean getElevatorNumber(){
        int applyId = getNowApplyId();
        ArrayList<StatisticBean> list = new ArrayList<>();
        if(applyId == -1){
            RealmResults<StatisticBean> listRealm = (RealmResults<StatisticBean>)this.realmManager.findAllByKey(StatisticBean.class,"type", "line");
            list = (ArrayList<StatisticBean>)this.realmManager.getRealm().copyFromRealm(listRealm);
        }else{
            RealmResults<StatisticBean> listRealm = (RealmResults<StatisticBean>)this.realmManager.findAllByKey(StatisticBean.class,"type", "apply","applyId",applyId);
            list = (ArrayList<StatisticBean>)this.realmManager.getRealm().copyFromRealm(listRealm);
        }

        if(list.size() != 0) {
            return list.get(0);
        }else{
            return new StatisticBean();
        }
    }

    public String getEleContractNo() {
        return eleContractNo;
    }

    public void setEleContractNo(String eleContractNo) {
        this.eleContractNo = eleContractNo;
    }
}
